import Taro from '@tarojs/taro'
const { rpc, fromNowOn } = require('../../utils/util.js')
const service = require('./service.js')
const regeneratorRuntime = require('../../utils/async.js')
const app = module.exports = {};

app.wxlogin = async (params, action, state) => {
  const data = await rpc(service.wxlogin, params)
  const { is_admin, token } = data
  const { userInfo = {} } = Taro.getApp().globalData

  Taro.getApp().globalData.userInfo = { ...userInfo, ...data }
  Taro.getApp().globalData.token = token
}

app.getList = async (params, action, state) => {
  const { key, pageIndex = 1, pageSize = 15 } = params
  const { articles } = state
  const dataMap = result => result;
  const suggested = Taro.getStorageSync('artcleSuggested');
  const artList = await rpc(
    service.getArticle, 
    { 
      filter_type: 'my_tags', 
      page: pageIndex, 
      per_page: pageSize, 
      last_suggested: suggested 
    }, 
    { dataMap }
  );
console.log('artList:', artList)
  articles[key] = articles[key] || {}
  articles[key].pageIndex = pageIndex
  articles[key].updateNum = artList.meta.number_of_update
  articles[key].showLoading = false
  articles[key].hasMore = pageSize * pageIndex < artList.number
  articles[key].articles = articles[key].articles || []
  articles[key].articles = articles[key].articles.concat(
    artList.data.map(art => ({
      ...art,
      articleImageVisible: art.post_img
        ? 'article-image show'
        : 'article-image hide',
      published: fromNowOn(new Date(art.published), 'yyyy-MM-dd hh:mm:ss')
    }))
  )
  console.log({articles})

  if (articles[key].articles.length) {
    Taro.setStorageSync('artcleSuggested', articles[key].articles[0].suggested)
  }
  await action.setData({ articles })
  return articles
}

app.loadMore = async (params, action, state) => {
  const { articles } = state
  const { key } = params

  articles[key].showLoading = true
  await action.setData({ articles })
  await action.dispatch('getList', params)
}

app.getMeAndTags = async (params, action, state) => {
  const me = await rpc(service.getMe)

  Taro.getApp().globalData.me = me

  if (!me.user_tags || me.user_tags.length === 0) {
    await action.dispatch('getTags')
  } else {
    action.setData({ showTagPanel: false, myTags: ['我的', ...me.user_tags] })
  }
}

app.getArtsByTags = async (params, action, state) => {
  const { myTags } = state
  const [all, ...tags] = myTags

  // 不使用for循环，异步操作也不会出错
  await Promise.all(
    tags.map(key => action.dispatch('getList', { page: 1, key, tag: key }))
  )
}

app.getTags = async (params, action, state) => {
  const tags = await rpc(service.getTags);
  const { subs } = tags;
  // const tagOrginList = Object.keys(tags).map(tagName => {
  //   return { name: tagName }
  // })
  const extraLength = 5 - (subs.length % 5);
  const extraArray = [...new Array(extraLength)].map(() => ({
    pos: true,
    name: '占位'
  }));

  await action.setData({ subs: [...subs, ...extraArray], showTagPanel: true })
}

app.saveTags = async (params, action, state) => {
  const { tags } = params
  const me = await rpc(service.setMe, { tags: tags.join(',') })

  action.dispatch('getMeAndTags')
}
